/**
 * 项目名：化工企业安全生产信息化管理平台
 * 日期：    2020-07-26 17:45:29
 * Copyright (c) 2015- -版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import javax.transaction.Transactional;

import com.joysuch.wwyt.bp.bean.BpDeviceFacilityStopRecoverRecordDetailBean;
import com.joysuch.wwyt.bp.bean.BpDeviceFacilityStopRecoverRecordEditBean;
import com.joysuch.wwyt.bp.bean.BpDeviceFacilityStopRecoverRecordListBean;
import com.joysuch.wwyt.bp.bean.BpDeviceFacilityStopRecoverRecordListBean.SearchBpDeviceFacilityStopRecoverRecord;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityStopRecoverRecord;
import com.joysuch.wwyt.bp.entity.BpMonitoringPointRel;
import com.joysuch.wwyt.bp.entity.BpProductionFacility;
import com.joysuch.wwyt.bp.entity.dsl.QBpDeviceFacilityStopRecoverRecord;
import com.joysuch.wwyt.bp.enums.ProductionFacilityStates;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpDeviceFacilityStopRecoverRecordDao;
import com.joysuch.wwyt.bp.repository.BpMonitoringPointRelDao;
import com.joysuch.wwyt.bp.repository.BpProductionFacilityDao;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityStopRecoverRecordService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.service.MhMonitoringPointService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import jodd.bean.BeanUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class BpDeviceFacilityStopRecoverRecordServiceImpl implements BpDeviceFacilityStopRecoverRecordService {

    @Autowired
    private BpDeviceFacilityStopRecoverRecordDao dao;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseAttachmentRepositoryService baseAttachmentRepositoryService;
    @Autowired
    private BpMonitoringPointRelDao relDao;
    @Autowired
    private MhMonitoringPointDao mhMonitoringPointDao;
    @Autowired
    private MhMonitoringPointService mhMonitoringPointService;

    @Override
    public BpDeviceFacilityStopRecoverRecord add(BpDeviceFacilityStopRecoverRecordEditBean entity) {
        BpDeviceFacilityStopRecoverRecord content = new BpDeviceFacilityStopRecoverRecord();
        BeanUtils.copyProperties(entity, content, "id");
        if (entity.getAttachment() != null) {
            content.setAttachmentId(entity.getAttachment().getId());
        }
        dao.save(content);
        checkFacilityState(content);
        return content;
    }

    private void checkFacilityState(BpDeviceFacilityStopRecoverRecord content) {
        BpProductionFacility facility = bpProductionFacilityDao.getOne(content.getDeviceFacilityId());
//        List<BpMonitoringPointRel> pfList = relDao.findByRefTypeAndRefId("production_facility", facility.getId());
        if ("S".equals(content.getType())) {
            facility.setState(ProductionFacilityStates.STOPED.getId());
            //2.3 设备停用复用不与监测点开关关联
//            setPointState(pfList, 0);
        } else {
            facility.setState(ProductionFacilityStates.RUNNING.getId());
//            setPointState(pfList, 1);
        }
    }

    //设备停用->所有监测点关闭 设备恢复->所有监测点开启
    private void setPointState(List<BpMonitoringPointRel> pfList, Integer state) {
        for (BpMonitoringPointRel rel : pfList) {
            Optional<MhMonitoringPoint> byId = mhMonitoringPointDao.findById(rel.getMonitoringPointId());
            if (byId.isPresent()) {
                mhMonitoringPointService.changeState(byId.get().getId(), state);
            }
        }
    }

    @Override
    public void update(BpDeviceFacilityStopRecoverRecordEditBean entity) {
        BpDeviceFacilityStopRecoverRecord content = dao.findById(entity.getId()).get();
        BeanUtils.copyProperties(entity, content, "id", "state");
        if (entity.getAttachment() != null) {
            content.setAttachmentId(entity.getAttachment().getId());
        } else {
            content.setAttachmentId(null);
        }
        dao.save(content);
        checkFacilityState(content);
    }

    @Override
    public Page<BpDeviceFacilityStopRecoverRecordListBean> findByPage(Pageable page,
                                                                      SearchBpDeviceFacilityStopRecoverRecord condition) {
        Predicate predicate = prepareListSearchCondition(condition);

        Page<BpDeviceFacilityStopRecoverRecord> data = predicate == null ? dao.findAll(page)
                : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpDeviceFacilityStopRecoverRecordListBean, BpDeviceFacilityStopRecoverRecord>() {

                    @Override
                    public BpDeviceFacilityStopRecoverRecordListBean convert(BpDeviceFacilityStopRecoverRecord f) {
                        BpDeviceFacilityStopRecoverRecordListBean bean = new BpDeviceFacilityStopRecoverRecordListBean();
                        SearchBpDeviceFacilityStopRecoverRecord searchBpDeviceFacilityStopRecoverRecord = new SearchBpDeviceFacilityStopRecoverRecord();
                        bean.setSearchBpDeviceFacilityStopRecoverRecord(searchBpDeviceFacilityStopRecoverRecord);
                        BeanUtils.copyProperties(f, bean);
                        BeanUtils.copyProperties(f, bean.getSearchBpDeviceFacilityStopRecoverRecord());
                        if (f.getRegisterUserId() != null) {
                            bean.setRegisterUserName(baseUserDao.getBaseUserNameById(f.getRegisterUserId()));
                        }
                        bean.setTypeName("S".equals(f.getType()) ? "停用" : "恢复");
                        return bean;
                    }

                });
    }

    private Predicate prepareListSearchCondition(SearchBpDeviceFacilityStopRecoverRecord condition) {
        Predicate p = null;
        QBpDeviceFacilityStopRecoverRecord q = QBpDeviceFacilityStopRecoverRecord.bpDeviceFacilityStopRecoverRecord;
        if (condition.getDeviceFacilityId() != null) {
            p = ExpressionUtils.and(p, q.deviceFacilityId.eq(condition.getDeviceFacilityId()));
        }
        if (condition.getType() != null) {
            p = ExpressionUtils.and(p, q.type.eq(condition.getType()));
        }
        if (condition.getRegisterUserId() != null) {
            p = ExpressionUtils.and(p, q.registerUserId.eq(condition.getRegisterUserId()));
        }
        if (condition.getStopReason() != null) {
            p = ExpressionUtils.and(p, q.stopReason.contains(condition.getStopReason()));
        }
        if (condition.getMeasuresAfterStop() != null) {
            p = ExpressionUtils.and(p, q.measuresAfterStop.contains(condition.getMeasuresAfterStop()));
        }
        if (condition.getRegisterTime() != null) {
            p = ExpressionUtils.and(p, q.registerTime.eq(condition.getRegisterTime()));
        }
        return p;
    }

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     *
     * @param id 要删除的业务ID
     */
    private void checkBussinessRestrictions(Long id) {
    }

    @Override
    public BpDeviceFacilityStopRecoverRecord findById(Long id) {
        return dao.findById(id).orElse(null);
    }

    /**
     * 删除
     *
     * @param recordId
     */
    @Override
    public void deleteById(Long recordId) {
        this.editFacilityState(recordId);
        dao.deleteById(recordId);
    }

    @Override
    public void batchAdd(BpDeviceFacilityStopRecoverRecordEditBean entity) {
        if (CollectionUtils.isNotEmpty(entity.getDeviceFacilityIds())) {
            List<Long> deviceFacilityIds=new ArrayList<>();
            List<BpDeviceFacilityStopRecoverRecord> list=new ArrayList<>();
            for (Long deviceFacilityId : entity.getDeviceFacilityIds()) {
                BpDeviceFacilityStopRecoverRecord content = new BpDeviceFacilityStopRecoverRecord();
                BeanUtils.copyProperties(entity, content, "id");
                if (entity.getAttachment() != null) {
                    content.setAttachmentId(entity.getAttachment().getId());
                }
                content.setDeviceFacilityId(deviceFacilityId);
                list.add(content);
                deviceFacilityIds.add(deviceFacilityId);
            }
            dao.saveAll(list);
            int state=ProductionFacilityStates.RUNNING.getId();
            if ("S".equalsIgnoreCase(entity.getType())){
                state=ProductionFacilityStates.STOPED.getId();
            }
            bpProductionFacilityDao.updateState(state,entity.getDeviceFacilityIds());
        }
    }

    //修改设备停用状态
    private void editFacilityState(Long recordId) {
        BpProductionFacility facility = bpProductionFacilityDao.getOneFromStopRecoverRecord(recordId);
        if (facility != null) {
            int sNum = dao.countByTypeAndDacilityIdAndIdNotEq("S", facility.getId(), recordId);
            int rNum = dao.countByTypeAndDacilityIdAndIdNotEq("R", facility.getId(), recordId);
            if (sNum > rNum) {
                facility.setState(ProductionFacilityStates.STOPED.getId());
            } else {
                facility.setState(ProductionFacilityStates.RUNNING.getId());
            }
            bpProductionFacilityDao.save(facility);
        }
    }

    @Override
    public BpDeviceFacilityStopRecoverRecordDetailBean getById(Long id) {
        BpDeviceFacilityStopRecoverRecord entity = findById(id);
        if (entity == null) {
            return null;
        }
        BpDeviceFacilityStopRecoverRecordDetailBean bean = new BpDeviceFacilityStopRecoverRecordDetailBean();
        BeanUtils.copyProperties(entity, bean);
        if (entity.getAttachmentId() != null) {
            bean.setAttachment(baseAttachmentRepositoryService.findByIdIntoBean(entity.getAttachmentId()));
        }
        if (entity.getRegisterUserId() != null) {
            bean.setRegisterUserName(baseUserDao.getBaseUserNameById(entity.getRegisterUserId()));
        }
        bean.setTypeName("S".equals(entity.getType()) ? "停用" : "恢复");
        return bean;
    }

}
